package idv.arthur.work;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

public class QuerySubSys extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public QuerySubSys() {
        super();
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	doPost(request,response);
    }

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		Widgets wid = new Widgets();
		request.setCharacterEncoding( wid.UIcodeSet );
		response.setContentType("application/json");
		response.setCharacterEncoding( wid.UIcodeSet );
		
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		String errPars = "}";
		
		String strSQL = "SELECT COUNT(*) FROM subsys";
		ResultTableSet resultTableSet = new ResultTableSet();
		
		String fromCall = request.getParameter("fc");
		
		final boolean isSU = Boolean.parseBoolean( request.getParameter("isSU") );
		
		int roleType = 0;
		final String currentUser = request.getParameter("loginUser");
		String whereCondition = "";		//依登入的帳號及角色，組合其where 子句
		
		
		if ( "delivery".equalsIgnoreCase(fromCall) ) {
			roleType = 1;
		} else  if ( "dep".equalsIgnoreCase(fromCall) || "revDep".equalsIgnoreCase(fromCall) ) {
			roleType = 3;
		} else if ( "mappingSquadHost".equalsIgnoreCase(fromCall)||"squad".equalsIgnoreCase(fromCall)||"mappingEnvSquad".equalsIgnoreCase(fromCall)||"env".equalsIgnoreCase(fromCall)||"host".equalsIgnoreCase(fromCall) ) {
			roleType = 4;
		} else {	 // Super User，將roleType設為 777
			roleType = 777;
		}
		
		if ( isSU ) {
			roleType = 777;
		} else {
			whereCondition = "t2.userid='"+currentUser+"' AND t2.roleid="+roleType;
		}
		
		
		ArrayList<InfoStruc> infoStrucs = new ArrayList<InfoStruc>();
		String sord = request.getParameter("sord");
		String sidx =  request.getParameter("sidx");
		String bss ="MBMS";
		
		int total_pages = 1;
		int count  = 0;
		int page = 1;
		int limit = 1000;
		
		if ("".equalsIgnoreCase(sidx)|| sidx==null) {
			sidx = "subsysname";
		} 
		if ("".equalsIgnoreCase(sord)|| sord==null) {
			sord = "ASC";
		} else {
			page = Integer.parseInt(request.getParameter("page"));
			limit = Integer.parseInt(request.getParameter("rows"));
		}
		
		try {
			conn = wid.getConn(true);	
			ps = conn.prepareStatement(strSQL);
			rs = ps.executeQuery();
			rs.next();
			count  = rs.getInt(1);
			
			if ( count  != 0 ) {
				
				if (limit  < count) {
					total_pages = (count / limit)+1;	
				}
				
				if ( roleType == 777 ) {
					if ( conn.getMetaData().getDatabaseProductName().contains( "MySQL" ) ) {
						strSQL = "SELECT t1.subsysid,t1.subsysname FROM subsys t1 WHERE t1.bssid=?  ORDER BY "+sidx+" "+sord+" LIMIT "+(limit*page-limit)+","+ limit;	
					} else if ( conn.getMetaData().getDatabaseProductName().contains( "Informix" ) ) {
						strSQL = "SELECT SKIP "+(limit*page-limit)+" FIRST "+ limit +" t1.subsysid, t1.subsysname FROM subsys t1 WHERE t1.bssid=?  ORDER BY "+sidx+" "+sord;
					}
				} else {
					if ( conn.getMetaData().getDatabaseProductName().contains( "MySQL" ) ) {
						strSQL = "SELECT t1.subsysid,t1.subsysname FROM subsys t1,mproleuser t2 WHERE "+whereCondition+" AND t1.bssid=t2.bssid AND t1.subsysid=t2.subsysid AND t1.bssid=?  ORDER BY "+sidx+" "+sord+" LIMIT "+(limit*page-limit)+","+ limit;	
					} else if ( conn.getMetaData().getDatabaseProductName().contains( "Informix" ) ) {
						strSQL = "SELECT SKIP "+(limit*page-limit)+" FIRST "+ limit +" t1.subsysid, t1.subsysname FROM subsys t1,mproleuser t2 WHERE "+whereCondition+" AND t1.bssid=t2.bssid AND t1.subsysid=t2.subsysid AND t1.bssid=? ORDER BY "+sidx+" "+sord;
					}
				}
				
				ps = conn.prepareStatement( strSQL );
				ps.setString(1, bss);
				
				rs = ps.executeQuery();
				ArrayList<Rows> rows = new ArrayList<Rows>();
				
				while ( rs.next() ) {
					String subSysId = rs.getString("subsysid");
					String subSysName = wid.DB2UI( rs.getString("subsysname"),conn.getMetaData().getDatabaseProductName() );
					
					if ( "delivery".equalsIgnoreCase(fromCall) || "dep".equalsIgnoreCase(fromCall) || "revDep".equalsIgnoreCase(fromCall) || "mappingSquadHost".equalsIgnoreCase(fromCall)||"squad".equalsIgnoreCase(fromCall)||"mappingEnvSquad".equalsIgnoreCase(fromCall)||"env".equalsIgnoreCase(fromCall)||"host".equalsIgnoreCase(fromCall)) {
						InfoStruc infoStruc = new InfoStruc();
						infoStruc.setId(subSysId);
						infoStruc.setName( subSysName );
						infoStrucs.add(infoStruc);
					} else {
						Rows row = new Rows();
						row.setId(subSysId);
						String[] cell = new String[2];
						cell[0] = subSysId;
						cell[1] = subSysName;
						row.setCell(cell);
						rows.add(row);
					}
				}
				resultTableSet.setRows( rows );
			} else {
				page =0;
				total_pages=0;
			}
			
			resultTableSet.setPage( String.valueOf(page) );
			resultTableSet.setTotal( total_pages );
			resultTableSet.setRecords(String.valueOf(count));
			
		} catch ( UnsupportedEncodingException e ) {
			wid.kem(conn, ps, e, wid.toEType("UnsupportedEncodingException")+errPars, wid.isPrint2Console );
		} catch ( SQLException e) {
			wid.kem(conn, ps, e, wid.toEType("SQLException")+errPars, wid.isPrint2Console );
		} catch ( Exception e) {
			wid.kem(conn, ps, e, wid.toEType("Exception")+errPars, wid.isPrint2Console );
		}  finally {
			try {
				if (rs != null) {rs.close();}
				if (ps!= null) {ps.close();}
				if (conn!= null) {conn.close();}
			} catch (SQLException e) {
				System.out.println( wid.errProcess(e) );
			}
		}
		
		if ( "delivery".equalsIgnoreCase(fromCall) || "dep".equalsIgnoreCase(fromCall) || "revDep".equalsIgnoreCase(fromCall) || "mappingSquadHost".equalsIgnoreCase(fromCall)||"squad".equalsIgnoreCase(fromCall)||"mappingEnvSquad".equalsIgnoreCase(fromCall)||"env".equalsIgnoreCase(fromCall)||"host".equalsIgnoreCase(fromCall)) {
			response.getWriter().write(new Gson().toJson(infoStrucs));
		} else{
			response.getWriter().write(new Gson().toJson(resultTableSet));	
		}
	}
}